<?php
/**
 * Svick a Fast Simple Smart PHP FrameWork
 * Author: Tommy 863758705@qq.com
 * Link: http://svick.tomener.com/
 * Since: 2022
 */

namespace lib\wechat;

use Exception;
use lib\qiniu\QiniuLib;
use model\user\User;
use Qiniu\Storage\BucketManager;
use Qiniu\Http\Error;
use Svick\Helper\Helper;
use Svick\Log\Log;

class AvatarLib
{
    /**
     * 抓取头像存储到七牛
     *
     * @param $uid
     * @param $head_img_url
     * @return bool
     * @throws Exception
     */
    public static function fetchAvatar($uid, $head_img_url)
    {
        if (empty($head_img_url)) {
            return true;
        }

        //构建鉴权对象
        $auth = QiniuLib::getAuth();

        //要上传的空间
        $bucket = QiniuLib::getBucket('avatar');

        $bucketManager = new BucketManager($auth);

        //指定抓取的文件保存名称
        $key = substr($uid, -4) . Helper::random(16); //从uid=2046550开始
        list(, $err) = $bucketManager->fetch($head_img_url, $bucket, $key);
        if ($err !== null) {
            /** @var $err Error */
            Log::single(['code' => $err->code(), 'message' => $err->message()], 'passport/fetch_head_pic');
            return false;
        }

        User::where(['id' => $uid])->update(['avatar' => $key]);
        return true;
    }
}
